import {attrs} from "./attrs";
import {directive,events} from "./directive";
export default class Ast{
  constructor(str,data,vm){
    this.data = data;
    this.str = str;
    this.ast = [];
    
    var strs = str.innerHTML;
    this.cs = {
      tag : "div",
      attrs:[{name:"class",value:"box"}],
      type:1,
      children:[{
        tag : "table",
        type:1,
        attrs:[],
        for:"arr",
        key:"index",
        alias:"item",
        children:[]
      }],

    }
    return this.exec(strs.trim());
  }
  exec(str){
    // console.log(str)
    // <div class="as">{{sige}}</div>
    var index = 0;
    var begin = /^\<([a-z]+[0-9]?)(\s[^\<]+)?\>/; 
    // begin = /^\<(\w+)\>/;
    var end = /^\<\/([a-z]+[0-9]?)\>/;
    var string = /^\{\{([a-z]+[0-9]?)\}\}/;
    var rest =  '';
    var stack = [];
    var stack2 = [{ children: [] }];
    while(index<str.length - 1){
      rest = str.substring(index)
      if(begin.test(rest)){
        console.log(rest)
        let tag = rest.match(begin)[1]
        let attrsString = rest.match(begin)[2]
        const attrStringLength = attrsString ? attrsString.length : 0
        stack.push(tag)
        stack2.push({
          tag:tag,
          type:1,
          children:[],
          attrs:attrs(attrsString),
          directives:directive(attrsString),
          events:events(attrsString)

        })
        index += tag.length + 2 + attrStringLength
        if(tag ==='input'){
          let pop_tag = stack.pop();
          let pop_arr = stack2.pop()
          if (stack2.length > 0) {
            stack2[stack2.length - 1].children.push(pop_arr)
          }
        }
        
      }else if(end.test(rest)){
        let tag = rest.match(end)[1];
        let pop_tag = stack.pop();
        if(tag === pop_tag){
          let pop_arr = stack2.pop()
          if (stack2.length > 0) {
            stack2[stack2.length - 1].children.push(pop_arr)
          }
        } else {
          throw new Error(tag + '标签没有封闭！！')
        }
        
        index += tag.length + 3
      }else if(string.test(rest)){
        let text = rest.match(string)[1];
        let text2 = rest.match(string)[0];
        // console.log(rest.match(string))
        if (!/^\s+$/.test(text)) {
          // 改变此时 stack2 栈顶元素
          stack2[stack2.length - 1].children.push({
            text:text2,
            type:3
          })
          
        }
        
        index += text.length + 4
      }else{
        index++
      }
      
    }
    console.log(stack2[0].children[0])
    // console.log(compilerToRenderFuntion(stack2[0].children[0]))
    return stack2[0].children[0];
  }
}